<template>
  <van-dialog
    v-model="visible"
    show-cancel-button
    :beforeClose="handleSubmit"
    confirm-button-color="rgba(25, 137, 250, 1.000)"
  >
    <div class="ip-container">
      <van-field
        v-model="ip"
        :error="hasError"
        required
        label="IP"
        placeholder="请输入IP地址"
      />
    </div>
  </van-dialog>
</template>
<script>
import { Dialog, Notify } from "vant";
import { isEmpty } from "ramda";
import { mapActions } from "vuex";
export default {
  name: "IPSetting",
  components: {
    [Dialog.Component.name]: Dialog.Component,
  },
  props: {
    value: {
      type: Boolean,
      required: true,
    },
  },
  data() {
    return {
      visible: this.show,
      hasError: false,
    };
  },
  computed: {
    ip: {
      get() {
        return this.$store.getters.ip;
      },
      set(val) {
        this.$store.commit("SET_IP", val);
      },
    },
  },
  watch: {
    value(val) {
      this.visible = val;
    },
    visible(val) {
      this.$emit("input", val);
    },
  },
  methods: {
    ...mapActions(["setIP"]),
    handleSubmit(action, done) {
      if (action === "confirm") {
        if (!isEmpty(this.ip.trim())) {
          this.setIP(this.ip)
            .then(() => {
              done();
            })
            .catch((e) => {
              Notify({ type: "danger", message: e });
              done(false);
            });
        } else {
          this.hasError = true;
          done(false);
        }
      } else {
        done();
      }
    },
  },
  mounted() {
    this.visible = this.value;
  },
};
</script>

<style scoped lang="less">
.ip-container {
  padding: 1rem;
}
</style>
